#!/usr/bin/perl
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
#  
#  
# Licensed Materials - Property of IBM 
#  
# Restricted Materials of IBM 
#  
# (C) COPYRIGHT International Business Machines Corp. 2002 
# All Rights Reserved 
#  
# US Government Users Restricted Rights - Use, duplication or 
# disclosure restricted by GSA ADP Schedule Contract with IBM Corp. 
#  
# IBM_PROLOG_END_TAG 
#
######################################################################
#                                                                    #
# Module: rmlcsext                                                   #
#                                                                    #
######################################################################
#                                                                    #
# Description: script to uninstall CSM/Director integration          #
#              extensions on CSM management servers and nodes        #
#                                                                    #
# Input:                                                             #
#   -A : uninstall Director Agent and CSM/Director agent             #
#   -C : uninstall Director Console components                       #
#   -S : uninstall Director Server components                        #
#   -h : show usage                                                  #
#   -v : verbose output                                              #
#                                                                    #
# Output: None                                                       #
#                                                                    #
# External references:                                               #
#         rpm --query                                                #
#         rpm --erase                                                #
#                                                                    #
# Return codes:                                                      #
#    0: Success                                                      #
#  1-4: Number of packages that failed to install                    #
#   96: Error with IBM Director operation                            #
#   97: RPM Error                                                    #
#   98: Missing pre-requisites                                       #
#   99: Parse Args Error                                             #
######################################################################
# sccsid = "@(#)95   1.3   src/csm/director/install/bin/rmlcsext.perl, csm.director, csm_rpyxh, rpyxht1f3 8/13/02 13:55:31"

use locale;
use Getopt::Std;
use File::Basename;

##################
# Global variables
##################
$progname  = basename($0); # program name as invoked
$rcode     = 0;            # Script return code
$rpm_rcode = 0;            # RPM call return code
$verbose   = 0;            # Verbose flag

$TWG_DIR          = ""; # IBM Director installed directory
$director_running = 0;  # State of Director agent before uninstall

$requested_to_remove = 0; # Number requested to remove
$packages_found = 0;      # Number of requested packages located
$packages_removed = 0;    # Number actually removed


######################################################################
# usage:
#     display usage message and exit
######################################################################
sub usage {
    print
      "Usage: $progname -h: Command usage syntax\n".
      "       $progname [-v] [-A] [-C] [-S]\n\n".
      "Options:\n".
      "    -A : try to uninstall csm.director.agent\n".
      "    -C : try to uninstall csm.director.console\n".
      "    -S : try to uninstall csm.director.server\n".
      "    -v : verbose output\n".
      "Default options are -A -C -S\n";
}


######################################################################
# parse_args:
#     parse and verify command line arguments
######################################################################
sub parse_args {
  if (!getopts('AChSv')) { &usage; exit(99); }

  if ($opt_h) { &usage; exit(0); }
  if ($opt_A) { if ($try_uninstall_agent++)   { &usage; exit(99);} }
  if ($opt_C) { if ($try_uninstall_console++) { &usage; exit(99);} }
  if ($opt_S) { if ($try_uninstall_server++)  { &usage; exit(99);} }
  if ($opt_v) { $verbose++; }

  if (!$opt_A && !$opt_C && !$opt_S) {
      # if no options specified, try everything
      $try_uninstall_agent   = 1;
      $try_uninstall_console = 1;
      $try_uninstall_server  = 1;
      $requested_to_remove = 3;
      $defaults_requested = 1;
  }
  else {
      $requested_to_remove =
        $try_uninstall_agent + $try_uninstall_console + $try_uninstall_server;
  }
}


######################################################################
# set_defaults:
#     setup values of variables used
######################################################################
sub set_defaults {
    # Replace this with more complicated logic (!) when we support more
    # platforms
    $rpmquery = "/bin/rpm --query";
    $queryfmt = "--queryformat \"%{NAME} %{VERSION} %{RELEASE} %{ARCH}\\n\"";

    $required_director_level = "4.10";
}


######################################################################
# determine_installed_sw:
#     locate/identify CSM/Director components already installed
######################################################################
sub determine_installed_sw {
  my($pkgs_to_query) = "csm.director.agent csm.director.console csm.director.server ITDAgent ITDServer";
  print "$rpmquery $pkgs_to_query $queryfmt\n" if $verbose;
  chomp(my(@rpmout)=`$rpmquery $pkgs_to_query $queryfmt`);
  my($rc) = $? >> 8;
  foreach $answer (@rpmout) {
      my($name,$version,$release,@rest) = split(/ /,$answer);
      print "name \"$name\" ".
            "version \"$version\" ".
            "release \"$release\" ".
            "rest \"@rest\"\n"
             if $verbose;
      if ($name ne "package") {
          $INSTALLED{$name} = $version;
      }
  }

  if ($verbose) {
      print "\nInstalled Packages:\n".
            "===================\n";
      for $pkg (keys %INSTALLED) {
          my($version) = $INSTALLED{$pkg};
          if ($version ne "") {
              print "$pkg $version\n";
          }
      }
      print "\n\n";
  }
}


######################################################################
# get_driector_status:
#     Determine if IBM director is running
#     side effect: sets TWG_DIR if it can be determined
######################################################################
sub get_director_status {
    # Determine location of IBM Director
    my($configFile);
    if (exists $INSTALLED{"ITDServer"}) {
        my($serverVer) = $INSTALLED{"ITDServer"};
        if ($serverVer ge $required_director_level) {
            $configFile = "/etc/TWGserver/TWGserver";
        }
    }
    elsif (exists $INSTALLED{"ITDAgent"}) {
        my($agentVer) = $INSTALLED{"ITDAgent"};
        if ($agentVer ge $required_director_level) {
            $configFile = "/etc/TWGagent/TWGagent";
        }
    }
    else { return; }

    if (!($openRc = open(TWGCONFIG, $configFile))) {
        print "Error: unable to open director configuration file $configFile\n";
    }
    else {
        my($line);
        while ($line = <TWGCONFIG>) {
            chomp($line);
            if ($line =~ /^\s*TWG_ROOTDIR\s*=\s*(\S+)\s*$/) {
                $TWG_DIR = $1;
            }
        }
    }
    close TWGCONFIG;

    if ($TWG_DIR eq "") {
        print "Unable to determine Director root directory\n";
        return;
    }

    print "Director root: $TWG_DIR\n" if $verbose;

    # Determine agent status
    print "$TWG_DIR/bin/twgstat\n" if $verbose;
    `/bin/ksh -c "$TWG_DIR/bin/twgstat > /dev/null 2>&1"`;
    my($rc) = $? >> 8;
    if ($rc == 0 || $rc == 1) {
        $director_running = 1;
    }
}


######################################################################
# stop_director
#     Stop director and wait for it to complete shutdown
######################################################################
sub stop_director {
    print "IBM Director Agent is running, stopping...\n";
    # Make sure agent is shut down before continuing
    print "$TWG_DIR/bin/twgend\n" if $verbose;
    `$TWG_DIR/bin/twgend`;
    my($rc) = 0;
    my($timeout_count) = 0;
    while ($rc != 3) {
        sleep(2);
        print "$TWG_DIR/bin/twgstat\n" if $verbose;
        `/bin/ksh -c "$TWG_DIR/bin/twgstat > /dev/null 2>&1"`;
        $rc = $? >> 8;
        print "twgstat rc=$rc\n" if $verbose;
        if ($timeout_count++ > 30) {
            print "Timeout stopping director server\n";
            exit(96);
        }
    }
}


######################################################################
# start_director
#     Start director agent
######################################################################
sub start_director {
    print "IBM Director Agent was running, restarting...\n";
    print "$TWG_DIR/bin/twgstart\n" if $verbose;
    `$TWG_DIR/bin/twgstart`;
}


######################################################################
# uninstall_rpm
#     locate RPM in searchpath and uninstall it
######################################################################
sub uninstall_rpm {
    my($pkgname) = @_;
    print "Uninstalling $pkgname:\t";
    `rpm --erase $pkgname`;
    $rc = $? >> 8;
    if ($rc) {
        print "Failed!\n";
        print "rcode=$rc\n" if $verbose;
        if ($rc > $rpm_rcode) { $rpm_rcode = $rc; }
    }
    else {
        print "Succeeded!\n";
    }
    return $rc;
}


######################################################################
# Mainline code
######################################################################
&parse_args;   # parse command line
&set_defaults; # setup default values

&determine_installed_sw; # locate pre-req / other sw installed

if ($try_uninstall_agent || $try_uninstall_server) {
    &get_director_status;
}


if ($try_uninstall_agent) {
    if (exists $INSTALLED{"csm.director.agent"}) {
        $packages_found++;
        if ($director_running) {
            $director_already_stopped = 1;
            &stop_director;
        }
        if (&uninstall_rpm("csm.director.agent") == 0) {
            $packages_removed++;
        }
    }
    elsif ($opt_A) {
        $rcode = 3;
    }
}

if ($try_uninstall_console) {
    if (exists $INSTALLED{"csm.director.console"}) {
        $packages_found++;
        if (&uninstall_rpm("csm.director.console") == 0) {
            $packages_removed++;
        }
    }
    elsif ($opt_C) {
        $rcode = 3;
    }
}

if ($try_uninstall_server) {
    if (exists $INSTALLED{"csm.director.server"}) {
        $packages_found++;
        if ($director_running && !$director_already_stopped) {
            &stop_director;
        }
        if (&uninstall_rpm("csm.director.server") == 0) {
            $packages_removed++;
        }
    }
    elsif ($opt_C) {
        $rcode = 3;
    }
}

if ($director_running) {
    &start_director;
}


if ($defaults_requested) {
    exit $rpm_rcode;
}
else {
    printf
      "Packages requested: $requested_to_remove\n".
      "Packages located:   $packages_found\n".
      "Packages removed:   $packages_removed\n";
    exit $rcode;
}
